﻿using System.Collections.Generic;
using Orchard.Localization;
using Ascent.XinKuanKong.Services;
using Orchard.FileSystems.AppData;
using Orchard.Logging;
using MongoDB.Driver;
using Top.Api;
using MongoDB.Bson.Serialization;
using Top.Api.Domain;

namespace Orchard.Indexing.Services
{
    public class XinKuanKongService : IXinKuanKongService
    {
        private readonly IOrchardServices _orchardServices;
        private readonly IAppDataFolder _appDataFolder;
        public Localizer T { get; set; }
        public ILogger Logger { get; set; }
        public XinKuanKongService(IOrchardServices orchardServices, IAppDataFolder appDataFolder)
        {
            _orchardServices = orchardServices;
            _appDataFolder = appDataFolder;
            T = NullLocalizer.Instance;
            Logger = NullLogger.Instance;
        }

        private const string connectionString = "";
        private MongoDatabase _mongoDatabase;
        public MongoDB.Driver.MongoDatabase MongoDatabase
        {
            get
            {
                if (_mongoDatabase == null)
                {
                    MongoServer server = MongoServer.Create(); // connect to localhost
                    _mongoDatabase = server.GetDatabase("xinkuankong");

                    if (!BsonClassMap.IsClassMapRegistered(typeof(Item)))
                    {
                        BsonClassMap.RegisterClassMap<Item>(cm =>
                        {
                            cm.AutoMap();
                            cm.SetIdMember(cm.GetMemberMap(e => e.NumIid));
                        });
                    }
                    if (!BsonClassMap.IsClassMapRegistered(typeof(Shop)))
                    {
                        BsonClassMap.RegisterClassMap<Shop>(cm =>
                        {
                            cm.AutoMap();
                            cm.SetIdMember(cm.GetMemberMap(e => e.Sid));
                        });
                    }
                }
                return _mongoDatabase;
            }
        }

        private const string serverUrl = "http://gw.api.taobao.com/router/rest";
        private const string appKey = "12152618";
        private const string appSecret = "20fadf5f6d959118128d55be8a1a9310";
        private const string sessionKey = "";
        private DefaultTopClient _defaultTopClient;
        public Top.Api.DefaultTopClient DefaultTopClient
        {
            get
            {
                if(_defaultTopClient == null)
                    _defaultTopClient = new DefaultTopClient(serverUrl, appKey, appSecret);
                return _defaultTopClient;
            }
        }
    }
}